<template>
	<custom-layout custom-class="custom-layout">
		<!--欢迎语  -->
		<view class="welcome">
			<view class="">
				您好，
			</view>
			<view class="">
				欢迎使用
			</view>
		</view>

		<view class="form">
			<!-- 表单 -->
			<wd-form ref="formRef" :model="formData" >
				
				<!-- <wd-cell-group border> -->
			
					<wd-input
					  custom-class="input"
					  prop="tenant"
					  clearable
					  v-model="formData.tenant"
					  placeholder="请输入公司"
					  :rules="[{ required: true, message: '请填写公司' }]"
					/>
				<wd-input
					  custom-class="input"
					  prop="username"
					  clearable
					  v-model="formData.username"
					  placeholder="请输入姓名"
					  :rules="[{ required: true, message: '请填写姓名' }]"
					/>
					<wd-input
					  custom-class="input"
					  prop="password"
					  show-password
					  clearable
					  v-model="formData.password"
					  placeholder="请输入密码"
					  :rules="[{ required: true, message: '请填写密码' }]"
					/>
				<!-- </wd-cell-group> -->
			</wd-form>
		</view>
		<!-- 提交 -->
		<wd-button block size="large" custom-class="submit-button" @click="handleSubmit">登录</wd-button>
		
	</custom-layout>
</template>

<script setup>
	import {
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		useDictionaryStore,
		useUserStore
	} from '@/store/index.js'
	import {
		getPhoneNumber,
		
	} from '@/api/user/info.js'
	import { getTenantIdByName } from '@/api/permission.js'
	import config from '@/config/index.js'
	import {
		onShow
	} from '@dcloudio/uni-app'

	// 字典仓库
	const dictionaryStore = useDictionaryStore()
	// 用户仓库
	const userStore = useUserStore()
	// 表单ref
	const formRef = ref()
	// 表单数据
	const formData = reactive({
		tenant: '顾好家',
		username: '',
		password: ''
		
	})
	watch(() => userStore.userInfo, () => {
		const keys = Object.keys(userStore.userInfo)
		if (keys.length > 1) {
			keys.forEach(key => {
				formData[key] = userStore.userInfo[key]
			})
		}
	}, {
		immediate: true
	})
	// 处理根据网站获取租户
	const handleGetTenantByWebsite =async () => {
	  const params = {
	    name:formData.tenant,
	  };
	  try {
	    const data = await getTenantIdByName(params)
	    userStore.tenantId = data;
	  } catch (error){
	    // 显示错误提示
	    setTimeout(() => {
	    	uni.showToast({
	    		title: error,
	    		icon: 'error'
	    	})
	    })
	  }
	};
	// 处理登录
	const handleSubmit = async () => {
		// 表单验证
		const validateResult = await formRef.value.validate();
		if (!validateResult.valid) return;
		await handleGetTenantByWebsite();
		try {
			console.log(22)

			// 显示加载提示
			uni.showLoading({
				mask: true
			});

			const params = {
				...formData,
			}
			await userStore.login(params);

			// 刷新缓存
			await userStore.getUserInfo()
			console.log(userStore.userId,'userId');
			
			// 获取字典列表
			dictionaryStore.getDictionaryList()
			uni.switchTab({
				url:'/pages/index/index'
			})

		} catch (error) {
			// 显示错误提示
			setTimeout(() => {
				 uni.showModal({
    			  title: '登录失败',
    			  content: typeof error === 'string' ? error : '未知错误',
    			  showCancel: false
    			});
			})
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
			
		
		}
	}
	// 处理获取手机号
	const handleGetPhoneNumber = ({
		code
	}) => {
		if (!code) {
			uni.showToast({
				title: '获取手机号失败',
				icon: 'error'
			})
			return
		}
		uni.showLoading({
			mask: true
		})
		getPhoneNumber({
			code
		}).then(data => {
			formData.mobile = data.phone_info.phoneNumber
		}).catch((error) => {
			setTimeout(() => {
				uni.showToast({
					title: error,
					icon: 'error'
				})
			})
		}).finally(() => {
			uni.hideLoading()
		})
	}
	// 处理获取头像
	const handleGetAvatar = ({
		avatarUrl
	}) => {
		uni.uploadFile({
			url: `${config.serverUrl[process.env.NODE_ENV]}/infra/file/upload`,
			filePath: avatarUrl,
			name: 'file',
			header: {
				'tenant-id': '1'
			},
			success: (res) => {
				const data = JSON.parse(res.data)
				if (data.code === 0) {
					formData.avatar = data.data
				} else {
					uni.showToast({
						title: data.msg,
						icon: 'error'
					})
				}
			},
			fail: () => {
				uni.showToast({
					title: '上传失败',
					icon: 'error'
				})
			}
		})
	}
	onShow(() => {

		// 隐藏home返回标识
        if (uni.hideHomeButton) {
           console.log('uni.hideHomeButton');
           wx.hideHomeButton();
        }
        
	})
</script>

<style lang="scss" scoped>
	// 自定义布局
	:deep(.custom-layout) {
		// background: #F8F8F8;
		background: #FFF url('~@/static/image/login-bg.jpg') no-repeat top / 100% auto;
	}
	// 欢迎语
	.welcome {
		padding: 10vh 20px 8vh;
		color: #fff;
		font-size: 18px;
	}
	.form {
		border-top-right-radius: 20px ;
		border-top-left-radius: 20px ;
	}
	// 上传样式
	:deep(.upload-style) {
		width: 120rpx !important;
		height: 120rpx !important;
	}

	// 登录按钮
	:deep(.submit-button) {
		margin: 10rpx 32rpx;
		background: #42bcff!important;
	}
	:deep(.input) {
		margin: 32rpx;;
		// background: #f6f6f8!important;
		// padding: 6rpx 10rpx;
		// border-radius: 20rpx;
	}
	:deep(.wd-input__value) {
		background: #f6f6f8!important;
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
	}
	:deep(.wd-input__error-message) {
		padding: 0 16rpx;
	}
	:deep(.wd-icon) {
		background: #f6f6f8!important;
	}
	:deep(.wd-input):after {
	  display: none !important;
	}
</style>